#include "logindialog.h"
#include "ui_logindialog.h"
#include "registerdialog.h"
#include "../widgets/doctor/doctorwidget.h"
#include "../widgets/patient/patientwidget.h"
#include "../network/networkclient.h"
#include <QMessageBox>
#include <QCryptographicHash>

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    setWindowTitle("智慧医疗平台登录");
    
    // 默认选择患者
    ui->patientRadio->setChecked(true);
    
    // 连接网络信号
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &LoginDialog::onMessageReceived);
}

LoginDialog::~LoginDialog() {
    delete ui;
}

bool LoginDialog::connectToServer() {
    if (!NetworkClient::instance().isConnected()) {
        QString host = NetworkClient::instance().defaultHost();
        quint16 port = NetworkClient::instance().defaultPort();
        if (!NetworkClient::instance().connectToServer(host, port)) {
            QMessageBox::critical(this, "连接失败", 
                QString("无法连接到服务器 %1:%2\n请确保服务器已启动").arg(host).arg(port));
            return false;
        }
    }
    return true;
}

void LoginDialog::on_loginButton_clicked() {
    QString username = ui->usernameEdit->text().trimmed();
    QString password = ui->passwordEdit->text();
    
    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入用户名和密码");
        return;
    }
    
    if (!connectToServer()) {
        return;
    }
    
    // 加密密码
    QString hashedPassword = QString(QCryptographicHash::hash(
        password.toUtf8(), QCryptographicHash::Sha256).toHex());
    
    // 发送登录请求
    QJsonObject request;
    request["username"] = username;
    request["password"] = hashedPassword;
    
    NetworkClient::instance().sendRequest(MSG_LOGIN, request);
}

void LoginDialog::on_registerButton_clicked() {
    // 打开注册对话框（注册界面内部有用户类型选择）
    RegisterDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        QMessageBox::information(this, "成功", "注册成功！请使用新账号登录");
    }
}

void LoginDialog::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_LOGIN_RESPONSE) {
        bool success = data["success"].toBool();
        QString message = data["message"].toString();
        
        if (success) {
            // 保存当前用户信息
            m_currentUser.id = data["id"].toInt();
            m_currentUser.username = data["username"].toString();
            m_currentUser.realName = data["real_name"].toString();
            m_currentUser.idCard = data["id_card"].toString();
            m_currentUser.phone = data["phone"].toString();
            m_currentUser.role = data["role"].toInt();
            
            // 检查用户类型是否匹配
            int expectedRole = ui->doctorRadio->isChecked() ? 2 : 1;
            if (m_currentUser.role != expectedRole) {
                QString roleStr = (expectedRole == 2) ? "医生" : "患者";
                QMessageBox::warning(this, "登录失败", 
                    QString("该账号不是%1账号，请重新选择身份").arg(roleStr));
                return;
            }
            
            // 根据角色创建对应的主窗口
            if (m_currentUser.role == 2) {
                // 医生
                Doctor doctor;
                doctor.id = m_currentUser.id;
                doctor.username = m_currentUser.username;
                doctor.realName = m_currentUser.realName;
                doctor.idCard = m_currentUser.idCard;
                doctor.phone = m_currentUser.phone;
                doctor.role = m_currentUser.role;
                doctor.departmentId = data["department_id"].toInt();
                doctor.departmentName = data["department_name"].toString();
                doctor.title = data["title"].toString();
                doctor.specialty = data["specialty"].toString();
                
                DoctorWidget *doctorWidget = new DoctorWidget(doctor);
                doctorWidget->show();
            } else {
                // 患者
                Patient patient;
                patient.id = m_currentUser.id;
                patient.username = m_currentUser.username;
                patient.realName = m_currentUser.realName;
                patient.idCard = m_currentUser.idCard;
                patient.phone = m_currentUser.phone;
                patient.role = m_currentUser.role;
                patient.gender = data["gender"].toString();
                patient.birthDate = QDate::fromString(data["birth_date"].toString(), "yyyy-MM-dd");
                patient.address = data["address"].toString();
                patient.emergencyContact = data["emergency_contact"].toString();
                
                PatientWidget *patientWidget = new PatientWidget(patient);
                patientWidget->show();
            }
            
            accept(); // 关闭登录对话框
        } else {
            QMessageBox::warning(this, "登录失败", message);
        }
    }
}

